import { createRouter, createWebHistory } from 'vue-router'
import useUserStore from '../store/userStore'

const routes = [
  {
    path: '/login',
    name: 'Login',
    meta: { name: '登录' },
    component: () => import('../views/Login/index.vue'),
  },
  {
    path: '/',
    name: 'Layout',
    meta: { name: '首页' },
    component: () => import('../views/Layout/index.vue'),

    children: [
      {
        path: '/',
        redirect: '/preview',
      },
      {
        path: 'preview',
        name: 'Preview',
        meta: { name: '数据概览' },
        component: () => import('../views/Preview/index.vue'),
      },
      {
        path: 'content-manager',
        name: 'ContentManager',
        meta: { name: '内容管理' },
        component: () => import('../views/ContentManager/index.vue'),
      },
      {
        path: 'post-article',
        name: 'PostArticle',
        meta: { name: '发布文章' },
        component: () => import('../views/PostArticle/index.vue'),
      },
      {
        path: 'user-info',
        name: 'UserInfo',
        meta: { name: '个人资料' },
        component: () => import('../views/UserInfo/index.vue'),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach((to, from) => {
  if (to.path !== '/login') {
    const token = useUserStore().token
    if (!token) {
      return '/login'
    }
  }
})

export default router
